package com.leyou.cart.service.impl;

import com.leyou.auth.entity.UserInfo;
import com.leyou.cart.interceptor.UserInterceptor;
import com.leyou.cart.pojo.Cart;
import com.leyou.cart.service.CartService;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptiion.LyException;
import com.leyou.common.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName CartServiceImpl
 * @Date 2019/2/27 9:08
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String KEY_PREFIX = "cart:userId:";

    @Override
    public void addCart(Cart cart) {
        //查询登陆的用户信息
        UserInfo user = UserInterceptor.getUserInfo();
        //key
        String key = KEY_PREFIX + user.getId();
        //hashKey
        String hashKey = cart.getSkuId().toString();
        BoundHashOperations<String, Object, Object> operation = redisTemplate.boundHashOps(key);
        Integer num = cart.getNum();
        //查询购物车商品是否存在
        if (operation.hasKey(hashKey)) {
            //存在，数量增加
            String json = operation.get(hashKey).toString();
            cart = JsonUtils.toBean(json, Cart.class);
            cart.setNum(cart.getNum() + num);
        }
        //写入redis
        operation.put(hashKey, JsonUtils.toString(cart));
    }

    @Override
    public void insertLocalCarts(List<Cart> carts) {
        //查询登陆的用户信息
        UserInfo user = UserInterceptor.getUserInfo();
        //key
        String key = KEY_PREFIX + user.getId();
        //查询购物车
        BoundHashOperations<String, Object, Object> operation = redisTemplate.boundHashOps(key);
        for (Cart cart : carts) {
            //判断是否已经存在购物项
            if (operation.hasKey(cart.getSkuId().toString())) {
                //已存在，增加数量
                Cart cacheCart = JsonUtils.toBean(operation.get(cart.getSkuId().toString()).toString(), Cart.class);
                cacheCart.setNum(cacheCart.getNum() + cart.getNum());
                operation.put(cart.getSkuId().toString(), JsonUtils.toString(cacheCart));
            } else {
                //不存在，添加
                operation.put(cart.getSkuId().toString(), JsonUtils.toString(cart));
            }
        }
    }

    @Override
    public List<Cart> queryCarts() {
        //取用户中的id
        UserInfo user = UserInterceptor.getUserInfo();
        String key = KEY_PREFIX + user.getId();
        if (!redisTemplate.hasKey(key)) {
            //如果用户购物车为空,返回404
            throw new LyException(ExceptionEnum.CART_NOT_FOUND);
        }
        //查询用户购物车
        BoundHashOperations<String, Object, Object> operation = redisTemplate.boundHashOps(key);
        List<Cart> carts = operation.values()
                .stream()
                .map(o -> JsonUtils.toBean(o.toString(), Cart.class))
                .collect(Collectors.toList());
        return carts;
    }

    @Override
    public void updateNum(Long skuId, Integer num) {
        //获取用户id
        UserInfo user = UserInterceptor.getUserInfo();
        String key = KEY_PREFIX + user.getId();
        BoundHashOperations<String, Object, Object> operation = redisTemplate.boundHashOps(key);
        if (!operation.hasKey(skuId.toString())) {
            throw new LyException(ExceptionEnum.CART_NOT_FOUND);
        }
        Cart cart = JsonUtils.toBean(operation.get(skuId.toString()).toString(), Cart.class);
        cart.setNum(num);
        operation.put(skuId.toString(), JsonUtils.toString(cart));
    }

    @Override
    public void deleteCart(String skuId) {
        //查询登陆的用户信息
        UserInfo user = UserInterceptor.getUserInfo();
        //key
        String key = KEY_PREFIX + user.getId();
        //查询购物车
        BoundHashOperations<String, Object, Object> operation = redisTemplate.boundHashOps(key);
        //删除购物项
        operation.delete(skuId);
    }
}
